package com.evolution.common.mybatis.autoconfigure;

import com.evolution.common.mybatis.autoconfigure.properties.MyBatisFlexExtendProperties;
import com.evolution.common.mybatis.dataobject.BaseDO;
import com.evolution.common.mybatis.decipher.CustomDataSourceDecipher;
import com.evolution.common.mybatis.listener.DataObjectInsertListener;
import com.evolution.common.mybatis.listener.DataObjectUpdateListener;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.audit.MessageCollector;
import com.mybatisflex.core.datasource.DataSourceDecipher;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.spring.boot.ConfigurationCustomizer;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import com.mybatisflex.spring.boot.MybatisFlexAutoConfiguration;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * Class: MyBatisFlexExtendAutoConfiguration
 * <p>
 * desc: Mybatis-Flex 全局配置类
 * </p>
 * create date: 2024-03-07 11:05:20
 *
 * @author cao.yong
 */
@AutoConfiguration
@AutoConfigureAfter(MybatisFlexAutoConfiguration.class)
@EnableConfigurationProperties(MyBatisFlexExtendProperties.class)
public class MyBatisFlexExtendAutoConfiguration implements ConfigurationCustomizer, MyBatisFlexCustomizer {

    protected final MyBatisFlexExtendProperties properties;

    public MyBatisFlexExtendAutoConfiguration(MyBatisFlexExtendProperties properties) {
        this.properties = properties;
    }

    /**
     * 数据源解密
     *
     * @return 加密实现对象
     */
    @Bean
    public DataSourceDecipher dataSourceDecipher() {
        return new CustomDataSourceDecipher();
    }

    @Override
    public void customize(FlexConfiguration configuration) {
        if (properties.isShowSql()) {
            configuration.setLogImpl(StdOutImpl.class);
        }
    }

    @Override
    public void customize(FlexGlobalConfig globalConfig) {
        // 注册监听器
        globalConfig.registerInsertListener(new DataObjectInsertListener(), BaseDO.class);
        globalConfig.registerUpdateListener(new DataObjectUpdateListener(), BaseDO.class);

        // 审计功能开关
        if (properties.isAuditEnabled()) {
            // 开启审计
            AuditManager.setAuditEnable(properties.isAuditEnabled());
            // 设置 SQL 审计收集器
            MessageCollector collector = new ConsoleMessageCollector();
            AuditManager.setMessageCollector(collector);
        }
    }
}
